from rest_framework import viewsets, status
from rest_framework.decorators import action, permission_classes
from rest_framework.response import Response
from rest_framework import generics, permissions
from .models import Blog
from .serializers import BlogSerializer, BlogCommentSerializer, BlogCategory, BlogCategorySerializer


class BlogViewSet(viewsets.ModelViewSet):
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer

    # 为不同操作设置不同的权限
    def get_permissions(self):
        if self.action in ['list', 'retrieve']:
            # 允许所有人查看博客列表和详情
            permission_classes = [permissions.AllowAny]
        elif self.action in ['create', 'update', 'partial_update', 'destroy', 'blog_comment']:
            # 只有认证用户可以创建、更新、删除博客
            permission_classes = [permissions.IsAuthenticated]
        else:
            permission_classes = [permissions.IsAuthenticated]
        return [permission() for permission in permission_classes]

    def retrieve(self, request, *args, **kwargs):
        blog = self.get_object()
        comments = blog.comments.all()
        blog_serializer = BlogSerializer(blog)
        comments_serializer = BlogCommentSerializer(comments, many=True)
        response_data = blog_serializer.data
        response_data['comments'] = comments_serializer.data
        return Response(response_data, status=status.HTTP_200_OK)
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save(author=request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    @action(detail=True, methods=['post'], url_path='comments')
    def blog_comment(self, request, pk=None):
        """评论功能需要登录"""
        blog = self.get_object()
        if request.method == 'POST':
            serializer = BlogCommentSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save(blog=blog, author=request.user)
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=['GET'])
    def my_blog(self, request):
        """获取当前用户的博客列表"""
        queryset = Blog.objects.filter(author=request.user)
        serializer = BlogSerializer(queryset, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['GET'])
    def recent_blog(self, request):
        """最近博客列表 - 允许所有人访问"""
        queryset = Blog.objects.all().order_by('-pub_time')[:5]
        serializer = BlogSerializer(queryset, many=True)
        return Response(serializer.data)


class BlogCategoryViewSet(viewsets.ModelViewSet):
    queryset = BlogCategory.objects.all()
    serializer_class = BlogCategorySerializer
    permission_classes = [permissions.IsAdminUser]
